import React, { Component } from "react";
import MainLayout from "../../../component/mainLayout/mainLayout";
import Button from "../../../component/button/index";
import AgreeCheckbox from "../../../component/agreeCheckbox/index";
import { connect } from "react-redux";
import { InputItem, Toast, Modal } from "antd-mobile";
import "./index.scss";
import verCode from "../../../component/verCode/index";
import BankItem from "./bankItem.js";
import {
	addNewBank,
	setSupportedBankList,
	getSelectedBankList,
	getSupportedBankList
} from "../../../Redux/Action/xhqbBank/bank";
import XHQBConfig from "../../../config/XHQBConfig";
import yhTools from "../../../tools/yh";
import { createForm } from "rc-form";

const BankIcon = require("../../../images/icon/helpTip.png");
const checkchinese = value => /[^\u4e00-\u9fa5]/.test(value);
const submitCardRegexp = value => value.replace(/\s*/g, "");
const checkPhoneReg = value => /^1[3456789]\d{9}$/.test(value);
const checkBankReg = value => /^\d{13,19}$/.test(value);
const checkIDReg = value =>
	/^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/.test(
		value
	);

@createForm()
@verCode()
@connect(
	state => ({
		supportedBankList: state.xhqbBankReducer.supportedBankList || []
	}),
	dispatch => ({
		addNewBank: value => dispatch(addNewBank(value)),
		setSupportedBankList: value => dispatch(setSupportedBankList(value)),
		getSelectedBankList: value => dispatch(getSelectedBankList(value)),
		getSupportedBankList: (value, fun) =>
			dispatch(getSupportedBankList(value, fun))
	})
)
class AddBank extends Component {
	constructor(props) {
		super(props);
		this.state = {
			isVisible: false,
			isRead: true,
			hasSendCode: false,
			bankcarbininformation: false,
			bankName: "",
			cardType: "",
			bankCode: "",
			tradeNo: "",
			haveUserInfo: false
		};
		this.channelCode = "YHB"; // 渠道号
		this.authLevel = ""; // 实名级别
		this.memberId = ""; // 会员号
	}
	componentDidMount = () => {
		const state = this.props.location.state || {};
		const { type } = state;
		this.isCloseApp = type === "closeApp"; // 关闭app
		this.getUserInfo();
	};
	/* 获取用户信息 */
	getUserInfo() {
		Toast.loading("加载中...", 1);
		let objs = {
			url: XHQBConfig.queryMemberAuthInfo,
			params: {},
			_alertShow: false
		};
		yhTools.request(objs).then(res => {
			// 获取支持的银行
			this.props.getSupportedBankList({ channelCode: this.channelCode });
			let { authLevel, mobile, memberId, memberName, maskCertId } = res.data;
			if (res.code === "0") {
				Toast.hide();
				// 更新认证等级
				this.authLevel = authLevel;
				this.memberId = memberId;
				const { setFieldsValue } = this.props.form;
				// 更新初始化数据
				setFieldsValue({
					userName: memberName,
					mobile,
					maskCertId
				});
				// 更新编辑状态
				this.setState({
					haveUserInfo: maskCertId && maskCertId !== ""
				});
			} else {
				Toast.info(res.message, 2);
			}
		});
	}
	/**展示支持银行卡列表 */
	toggleVisible = isVisible => {
		this.setState({
			isVisible
		});
	};
	/**发送短信验证码 */
	sendMsgCode = () => {
		const {
			bankName,
			bankCode,
			cardType,
			bankcarbininformation,
			haveUserInfo
		} = this.state;
		const { sendCode, isClick, setCountDown } = this.props.verCode;
		const { getFieldsValue } = this.props.form;
		let {
			accountNo = "",
			userName = "",
			maskCertId = "",
			mobile = ""
		} = getFieldsValue(["accountNo", "userName", "maskCertId", "mobile"]);
		// 过滤空格
		accountNo = submitCardRegexp(accountNo);
		mobile = submitCardRegexp(mobile);

		if (checkchinese(userName)) {
			Toast.info("持卡人格式不正确", 2);
			return false;
		}
		if (!userName) {
			Toast.info("请填写持卡人", 2);
			return false;
		}
		if (!mobile) {
			Toast.info("请填写手机号", 2);
			return false;
		}
		if (!checkBankReg(accountNo)) {
			Toast.info("银行卡格式不正确", 2);
			return false;
		}
		if (!accountNo) {
			Toast.info("请填写银行卡号", 2);
			return false;
		}
		if (!maskCertId) {
			Toast.info("请填写证件号码", 2);
			return false;
		}
		if (!checkPhoneReg(mobile)) {
			Toast.info("手机号格式不正确", 2);
			return false;
		}
		if (!haveUserInfo && !checkIDReg(maskCertId)) {
			Toast.info("证件号码格式不正确", 2);
			return false;
		}
		if (!bankcarbininformation) {
			Toast.info("卡Bin校验失败", 2);
			return;
		}
		if (!isClick) return;

		setCountDown(60); //连连和华通验证码时间不一样

		let objs = {
			url: XHQBConfig.applySign,

			params: {
				bankAccNo: accountNo, //银行卡号
				bankAccName: userName, //用户名
				bankName, //银行名称
				bankCode, //银行编号
				cardType, //卡类型
				certType: "ID",
				certId: maskCertId, //证件号码
				reserveMobile: mobile, //预留手机号
				memberId: this.memberId, //金融会员号
				authLevel: this.authLevel //实名级别
			},
			_alertShow: false
		};
		Toast.loading("加载中...", 100);

		yhTools.request(objs).then(res => {
			Toast.hide();
			if (res.code === "0") {
				sendCode();
				const { tradeNo } = res.data;
				Toast.info("验证码发送成功", 2);
				this.setState({
					tradeNo,
					hasSendCode: true
				});
			} else {
				Toast.info(res.message, 2);
			}
		});
	};
	/**协议勾选 */
	toggleAgree = () => {
		this.setState(prevState => {
			return { isRead: !prevState.isRead };
		});
	};
	/**提交参数检测 */
	checkCanSubmit = (cardNo, mobile, verifyCode) => {
		if (!cardNo) {
			Toast.info("请输入银行卡号", 2);
			return false;
		}
		if (!checkBankReg(cardNo)) {
			Toast.info("请输入正确的银行卡号", 2);
			return false;
		}
		if (!mobile) {
			Toast.info("请填写手机号", 2);
			return false;
		}
		if (!checkPhoneReg(mobile)) {
			Toast.info("手机号格式不正确", 2);
			return false;
		}
		if (!verifyCode.length) {
			Toast.info("请输入验证码");
			return false;
		}
		if (verifyCode.length !== 6) {
			Toast.info("验证码输入错误");
			return false;
		}
		if (!this.state.isRead) {
			Toast.info("请勾选协议");
			return false;
		}
		return true;
	};
	/**请求添加银行卡 */
	addNewBankFn = () => {
		const { tradeNo } = this.state;
		const { getFieldValue } = this.props.form;
		let accountNo = getFieldValue("accountNo") || "";
		let mobile = getFieldValue("mobile") || "";
		let verifyCode = getFieldValue("verifyCode") || "";
		// 过滤空格
		accountNo = submitCardRegexp(accountNo);
		mobile = submitCardRegexp(mobile);
		if (this.checkCanSubmit(accountNo, mobile, verifyCode)) {
			if (!this.state.hasSendCode) {
				return Toast.info("验证码输入错误");
			}
			let objs = {
				url: XHQBConfig.confirmSign,
				params: {
					tradeNo,
					verifyCode
				},
				_alertShow: false
			};
			Toast.loading("加载中...", 100);
			yhTools.request(objs).then(res => {
				Toast.hide();
				if (res.code === "0") {
					if (res.data.status == 0) {
						Toast.info("添加成功", 2);
						setTimeout(() => {
							if (this.isCloseApp) {
								yhTools.closePage();
							} else {
								this.props.history.goBack();
							}
						}, 1000);
					} else {
						Toast.info(res.data.msg, 2);
					}
				} else {
					Toast.info(res.message, 2);
				}
			});
		}
	};
	/**点击确认绑定 */
	saveBank = () => {
		this.addNewBankFn();
	};
	/* 查看银行卡Bin */
	checkcardBin() {
		const { getFieldValue } = this.props.form;
		let accountNo = getFieldValue("accountNo");
		// 过滤空格
		accountNo = submitCardRegexp(accountNo);
		if (!accountNo) {
			Toast.info("请输入银行卡号", 2);
			return true;
		}
		if (!checkBankReg(accountNo)) {
			Toast.info("请输入正确的银行卡号", 2);
			return true;
		}
		let objs = {
			url: XHQBConfig.queryCardBin,
			params: {
				bankAccNo: accountNo
			},
			_alertShow: false
		};
		Toast.loading("加载中...", 100);
		yhTools.request(objs).then(res => {
			Toast.hide();
			if (res.code === "0") {
				const { bankName, cardType, bankCode } = res.data;
				this.setState({
					bankcarbininformation: true,
					bankName,
					cardType,
					bankCode
				});
			} else {
				this.setState(
					{
						bankcarbininformation: false,
						bankName: "",
						cardType: "",
						bankCode: ""
					},
					() => {
						Toast.info(res.message, 2);
					}
				);
			}
		});
	}
	//查看支付协议
	gotopaycontract = e => {
		e.stopPropagation();
		this.props.history.push("/paymentagreementdisplay");
	};

	showModal = () => {
		this.setState({
			isVisible: false,
			isBackModalVisible: true
		});
	};

	verifyCodeBlur() {
		this.contentScrollTop("0rem");
	}
	verifyCodeFocus() {
		this.contentScrollTop("-1.4rem");
	}
	contentScrollTop(num) {
		const { bankcarbininformation } = this.state;
		if (bankcarbininformation) {
			let pDom = document.getElementsByClassName("add-bank-container")[0];
			if (pDom) {
				pDom.style.marginTop = num;
			}
		}
	}
	render() {
		const {
			isVisible,
			isRead,
			bankcarbininformation,
			hasSendCode,
			bankName,
			cardType,
			haveUserInfo
		} = this.state;
		const { supportedBankList } = this.props;
		const _pageParams = {
			header: {
				title: "添加银行卡",
				goToApp: this.isCloseApp
			},
			history: this.props.history,
			cacheLifecycles: this.props.cacheLifecycles
		};
		const { countDown, isClick } = this.props.verCode;
		const { getFieldProps } = this.props.form;
		return (
			<div>
				<MainLayout pageParams={_pageParams} handleBack={this.showModal}>
					<div className="add-bank-container">
						<InputItem
							type="text"
							className="my-input"
							disabled={haveUserInfo}
							{...getFieldProps("userName")}
							placeholder="请输入持卡人"
							maxLength="30"
						>
							持卡人
						</InputItem>
						<InputItem className="my-input" defaultValue={`身份证`} disabled>
							证件类型
						</InputItem>
						<InputItem
							maxLength="18"
							clear
							disabled={haveUserInfo}
							placeholder="请输入证件号码"
							{...getFieldProps("maskCertId")}
							className="my-input"
						>
							证件号码
						</InputItem>
						{/* 23包括空格 */}
						<InputItem
							maxLength="23"
							className="my-input my-clear1"
							placeholder="请输入银行卡号"
							type="bankCard"
							{...getFieldProps("accountNo")}
							onBlur={this.checkcardBin.bind(this)}
						>
							银行卡号
							<img
								alt="guide"
								className="icon-help"
								src={BankIcon}
								onClick={() => this.toggleVisible(true)}
							/>
						</InputItem>
						{bankcarbininformation && (
							<React.Fragment>
								<InputItem
									clear
									type="phone"
									value={bankName}
									className="my-input"
									disabled
								>
									开户银行
								</InputItem>
								<InputItem
									clear
									type="phone"
									value={cardType === "DE" ? "借记卡" : "信用卡"}
									className="my-input"
									disabled
								>
									卡类型
								</InputItem>
							</React.Fragment>
						)}
						<InputItem
							clear
							type="phone"
							placeholder="请填写预留手机号"
							className="my-input"
							onFocus={this.contentScrollTop.bind(this, "-0.6rem")}
							onBlur={this.contentScrollTop.bind(this, "0rem")}
							{...getFieldProps("mobile")}
						>
							预留手机号
						</InputItem>
						<InputItem
							clear
							placeholder="请输入验证码"
							maxLength={6}
							minLength={6}
							pattern="[0-9]{6}"
							type="tel"
							className="my-input my-clear2"
							onFocus={this.verifyCodeFocus.bind(this)}
							onBlur={this.verifyCodeBlur.bind(this)}
							{...getFieldProps("verifyCode")}
						>
							验证码
							<span className="get-code" onClick={this.sendMsgCode}>
								{isClick
									? hasSendCode
										? "重新发送"
										: "获取验证码"
									: countDown}
							</span>
						</InputItem>
						<div className="agree-wrapper">
							<AgreeCheckbox
								checked={isRead}
								onChange={() => this.toggleAgree()}
							>
								<React.Fragment>
									本人同意并签署
									<a className="font-link" onClick={this.gotopaycontract}>
										《支付协议》
									</a>
								</React.Fragment>
							</AgreeCheckbox>
						</div>

						<Modal
							visible={isVisible}
							transparent
							maskClosable={true}
							title="银行卡支持列表"
							closable={true}
							onClose={() => this.toggleVisible(false)}
							className="bank-list-modal"
						>
							<div style={{ height: 300, overflow: "scroll" }}>
								{supportedBankList.map(item => (
									<BankItem item={item} key={Math.random()} />
								))}
							</div>
						</Modal>

						<Button
							style={{ marginTop: "60px" }}
							onClick={this.saveBank.bind(this)}
						>
							确认绑定
						</Button>
					</div>
				</MainLayout>
			</div>
		);
	}
}
export default AddBank;
